<template>
  <AdVxeModal
    v-bind="$attrs"
    @register="register"
    :id="formIndex"
    :title="`${t('mobile.route.app.title')} - ${FormModeEntityRef.Display}`"
    :help-message="`${t('common.form')}：${formIndex}`"
    :cancelText="t('common.cancelText')"
    :close-func="handleClose"
    :okText="FormModeEntityRef.OkBtnTitle"
    @ok="handleOk"
    @open-change="handleOpenChange"
    width="50%"
  >
    <BasicForm @register="registerForm" @contextmenu="handleContextMenu">
      <template #icon="{ model, field }">
        <ImageSelector
          v-model:value="model[field]"
          :width="50"
          accept=".jpg,.jpeg,.png,.bmp,.ico,.gif"
          :max-size="0.5"
          :disabled="
            FormModeEntityRef.FormMode !== FormModeEnum.Add &&
            FormModeEntityRef.FormMode !== FormModeEnum.Edit
          "
        />
      </template>
    </BasicForm>
  </AdVxeModal>

  <PrintTemplateModal @register="templateModalRegister" v-bind="templateModalProps" />
</template>

<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { ref } from 'vue';

  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { BasicForm } from '@/components/Form';
  import { PrintTemplateModal, useAdPrint } from '@/components/AdPrint';
  import { ImageSelector } from '@/components/ImageSelector';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useContextMenu } from '@/hooks/web/useContextMenu';
  import { destroyContextMenu } from '@/components/ContextMenu';
  import { isFunction } from '@/utils/is';

  import { FormModeEnum, FormModeEntity } from '@/enums/formEnum';

  import { AjaxResult } from '#/request';
  import { AppInputDtoSimple, AppOutputDtoSimple } from '@/api/mobile/model/app';
  import { createApp, updateAppSimple, deleteApp } from '@/api/mobile/admin/app';

  import { registerForm, resetFields, getFieldsValue, setFieldsValue, validate } from './detail';

  defineOptions({ name: 'MobAppDetailModal' });
  const props = defineProps({
    /** 关闭回调，返回true关闭窗体 */
    closeFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, record?: AppOutputDtoSimple) => Promise<boolean>
      >,
      default: null,
    },
    /** 提交前回调，返回false不执行内置提交逻辑，返回true执行内置提交逻辑 */
    beforeSubmitFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, record?: AppOutputDtoSimple) => Promise<boolean>
      >,
      default: null,
    },
    /** 提交后回调，返回true关闭窗体 */
    afterSubmitFunc: {
      type: Function as PropType<
        (
          formMode: FormModeEnum,
          result?: AjaxResult | null,
          record?: AppOutputDtoSimple,
        ) => Promise<boolean>
      >,
      default: null,
    },
  });

  const { t } = useI18n();
  const [createContextMenu] = useContextMenu();
  const formIndex = 'ea_mobile_app_detail';
  const keyField = 'Id';

  const formModeRef = ref<FormModeEnum>(FormModeEnum.Ok);
  const FormModeEntityRef = ref<FormModeEntity>(new FormModeEntity(formModeRef.value));

  const [register, { setModalProps, closeModal, changeLoading }] = useModalInner(async (data) => {
    changeLoading(true);
    try {
      await clearInputDto();
      const record = data.record;
      if (data.formMode) {
        formModeRef.value = data.formMode as FormModeEnum;
        FormModeEntityRef.value = new FormModeEntity(formModeRef.value);
        switch (formModeRef.value) {
          case FormModeEnum.Add:
            break;
          case FormModeEnum.Edit:
          case FormModeEnum.ReadOnly:
          case FormModeEnum.Ok:
            // const result = await getTemplateFile(record.Id);
            // if (result?.Type === 200) {
            //   const outputDto = result.Data as QueryMessageOutputDto;
            //   // console.log(templateFileOutputDto);
            //   if (outputDto) {
            //     await setInputDto({
            //       TemplateFile: { ...outputDto },
            //     });
            //   }
            // }
            break;
        }
      }
      if (record) {
        await setInputDto({
          ...record,
        });
      }
    } finally {
      changeLoading(false);
    }
  });

  //#region "加载状态"
  const loadingRef = ref(false);
  /** 开启加载状态 */
  function openLoading() {
    changeLoading(true);
    setModalProps({ okLoading: true, cancelLoading: true });
    loadingRef.value = true;
  }
  /** 关闭加载状态 */
  function closeLoading() {
    changeLoading(false);
    setModalProps({ okLoading: false, cancelLoading: false });
    loadingRef.value = false;
  }
  //#endregion
  //#region 定义高级打印
  const { printContextMenus, templateModalRegister, templateModalProps } = useAdPrint({
    formIndex: formIndex,
    keyField: keyField,
    getFormData: () => getInputDto(),
  });
  /** 处理上下文菜单(右键菜单) */
  function handleContextMenu(e: MouseEvent) {
    const element = document.elementFromPoint(e.clientX, e.clientY) as Element;
    const cursor = document.defaultView?.getComputedStyle(element, null).cursor;
    // console.log('handleContextMenu', {
    //   cursor: cursor,
    // });

    let items: any[] = [];
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Ok:
      case FormModeEnum.Edit:
      case FormModeEnum.ReadOnly:
        if (!cursor || cursor === 'default' || cursor === 'auto') {
          items = [...printContextMenus];
        }
        break;
    }
    if (items && items?.length > 0) {
      createContextMenu({
        event: e,
        styles: {
          border: '1px solid #eee',
          'border-radius': '2px',
          'box-shadow': '3px 3px 3px rgb(0 0 0 / 15%)',
        },
        items: [...items],
      });
    }
  }
  //#endregion

  /** 获取输入DTO */
  function getInputDto(): AppInputDtoSimple {
    const record = { ...getFieldsValue() } as AppInputDtoSimple;
    return record;
  }
  /** 设置输入DTO */
  async function setInputDto(values: any) {
    let inputDto = getInputDto() as any;
    inputDto = { ...inputDto, ...values };
    await setFieldsValue({ ...inputDto });
  }
  /** 清除输入DTO */
  async function clearInputDto() {
    await resetFields();
  }

  /** 获取输出DTO */
  function getOutputDto(): AppOutputDtoSimple {
    const record = { ...getFieldsValue() } as AppOutputDtoSimple;
    return record;
  }

  /** 处理关闭按钮 */
  async function handleClose() {
    openLoading();

    const { closeFunc } = props;
    try {
      if (closeFunc && isFunction(closeFunc)) {
        const outputDto = getOutputDto();
        const result = await closeFunc(FormModeEntityRef.value.FormMode, outputDto);
        return result;
      }
    } finally {
      closeLoading();
    }
    return true;
  }
  /** 处理确定按钮 */
  async function handleOk() {
    // 数据校验
    let data = await validate();
    if (!data) return;

    openLoading();
    const { beforeSubmitFunc, afterSubmitFunc } = props;
    try {
      const inputDto = getInputDto();
      const outputDto = getOutputDto();
      // console.log('handleOk', inputDto);
      let innerSubmit = true;
      let innerCloseModal = true;
      if (beforeSubmitFunc && isFunction(beforeSubmitFunc)) {
        innerSubmit = await beforeSubmitFunc(FormModeEntityRef.value.FormMode, outputDto);
      }
      let result: AjaxResult | null = null;
      if (innerSubmit) {
        switch (FormModeEntityRef.value.FormMode) {
          case FormModeEnum.Add:
            const dtos = [{ ...inputDto, Versions: [] }];
            result = await createApp(dtos);
            break;
          case FormModeEnum.Edit:
            result = await updateAppSimple([inputDto]);
            break;
          case FormModeEnum.Delete:
            result = await deleteApp([inputDto.Id]);
            break;
        }
      }
      if (afterSubmitFunc && isFunction(afterSubmitFunc)) {
        innerCloseModal = await afterSubmitFunc(
          FormModeEntityRef.value.FormMode,
          result,
          outputDto,
        );
      }
      if (innerCloseModal) {
        closeModal();
      }
    } finally {
      closeLoading();
    }
  }

  /** 打开或者关闭触发 */
  function handleOpenChange(open: boolean) {
    if (!open) {
      destroyContextMenu();
    }
  }
</script>

<style lang="less" scoped>
  .qr-code {
    margin: 0 auto;
    margin-bottom: 15px;
    text-align: center;
  }

  .context-menu {
    z-index: 8888 !important;
  }
</style>
